package com.example.pro1.controller.zhao;

import com.example.pro1.config.zhao.WebSocketConfig;
import com.example.pro1.service.zhao.chat.GetHttpSessionConfigratiom;
import com.google.gson.Gson;
import org.springframework.boot.autoconfigure.condition.ConditionalOnClass;
import org.springframework.context.ApplicationContext;
import org.springframework.stereotype.Component;
import org.springframework.web.bind.annotation.CrossOrigin;

import javax.servlet.http.HttpSession;
import javax.websocket.*;
import javax.websocket.server.ServerEndpoint;
import java.io.IOException;
import java.util.HashMap;
import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;
@Component
@ServerEndpoint("/chat/dd")
@ConditionalOnClass(value = WebSocketConfig.class)
@CrossOrigin//开放前端跨域访问
public class chatv1 {

    //lainjie容器
    private static Map<String,chatv1> online=new ConcurrentHashMap<>();

    private Session session;

    private HttpSession httpSession;

    private static ApplicationContext applicationContext;


    //连接建立
    @OnOpen
    public void Onopen(Session session , EndpointConfig endpointConfig)
    {
        this.session=session;
        this.httpSession= (HttpSession) endpointConfig.getUserProperties().get(HttpSession.class.getName());
        String name= (String) httpSession.getAttribute("user");

        //fangru容器
        online.put(name,this);
    }
    @OnClose
    public void OnClose(String message,Session session)
    {

    }
    @OnError
    public void OnError()
    {

    }
    //收到信息时
    @OnMessage
    public void OnMessage(String message,Session session) throws IOException {
        Gson gson = new Gson();
        HashMap<String,String> hashMap = gson.fromJson(message, HashMap.class);

        String who= (String) this.httpSession.getAttribute("user");
        String towho=hashMap.get("towho");
        String what=hashMap.get("what");

        chatv1 s=online.get(towho);
        if(s!=null)//对方在线直接发送
        {
            s.session.getBasicRemote().sendText(message);
        }
        //不管在不在存入数据库


    }
}

